import React, { useState, useEffect } from 'react';
import './ClassPage.css';
import ClassTable from './components/ClassTable';
import AddEditClassModal from './components/AddEditClassModal';
import ConfirmModal from './components/ConfirmModal';
import ClassDetailModal from './components/ClassDetailModal';
import { Class } from '../../shared/models';
import { useData } from '../../shared/DataContext';

const ClassPage: React.FC = () => {
  // 使用数据上下文获取班级数据和操作方法
  const { classes, students, addClass, updateClass, deleteClass, addAuditLog } = useData();
  
  const [filteredClasses, setFilteredClasses] = useState<Class[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedStage, setSelectedStage] = useState('');
  const [selectedAcademy, setSelectedAcademy] = useState('');
  const [selectedStatus, setSelectedStatus] = useState('');
  const [showAddEditModal, setShowAddEditModal] = useState(false);
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [showDetailModal, setShowDetailModal] = useState(false);
  const [selectedClass, setSelectedClass] = useState<Class | null>(null);
  const [isEditing, setIsEditing] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const itemsPerPageOptions = [5, 10, 20, 50]; // 每页显示条数选项

  // 计算总页数
  const totalPages = Math.ceil(filteredClasses.length / itemsPerPage);

  // 处理每页显示条数变化
  const handleItemsPerPageChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setItemsPerPage(parseInt(e.target.value, 10));
    setCurrentPage(1); // 重置到第一页
  };

  // 跳转到指定页码
  const handlePageJump = (pageNum: number) => {
    if (pageNum >= 1 && pageNum <= totalPages) {
      setCurrentPage(pageNum);
    }
  };

  // 快速跳转到首页或末页
  const goToFirstPage = () => setCurrentPage(1);
  const goToLastPage = () => setCurrentPage(totalPages);

  // 过滤班级数据
  useEffect(() => {
    let result = [...classes];

    // 按名称、编号搜索
    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      result = result.filter(
        cls =>
          cls.name.toLowerCase().includes(term) ||
          cls.id.toLowerCase().includes(term) ||
          (cls.advisorName && cls.advisorName.toLowerCase().includes(term)) ||
          (cls.lecturerName && cls.lecturerName.toLowerCase().includes(term))
      );
    }

    // 按阶段过滤
    if (selectedStage) {
      result = result.filter(cls => cls.stage === selectedStage);
    }

    // 按学院过滤
    if (selectedAcademy) {
      result = result.filter(cls => cls.academy === selectedAcademy);
    }

    // 按状态过滤
    if (selectedStatus) {
      result = result.filter(cls => cls.status === selectedStatus);
    }

    setFilteredClasses(result);
    setCurrentPage(1); // 重置到第一页
  }, [classes, searchTerm, selectedStage, selectedAcademy, selectedStatus]);

  // 分页逻辑
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentClasses = filteredClasses.slice(indexOfFirstItem, indexOfLastItem);

  // 处理查看班级详情
  const handleViewDetail = (cls: Class) => {
    setSelectedClass(cls);
    setShowDetailModal(true);
    // 添加审计日志
    addAuditLog({
      action: 'VIEW_CLASS',
      entity: 'class',
      entityId: cls.id,
      details: `查看班级详情: ${cls.name}`
    });
  };

  // 处理添加班级
  const handleAddClass = () => {
    setSelectedClass(null);
    setIsEditing(false);
    setShowAddEditModal(true);
  };

  // 处理编辑班级
  const handleEditClass = (cls: Class) => {
    setSelectedClass(cls);
    setIsEditing(true);
    setShowAddEditModal(true);
  };

  // 处理删除班级
  const handleDeleteClass = (cls: Class) => {
    // 检查是否有关联的学生
    const classHasStudents = students.some(student => student.classId === cls.id);
    if (classHasStudents) {
      alert(`无法删除班级「${cls.name}」，该班级还有关联的学生。请先将学生转移或删除。`);
      return;
    }
    
    setSelectedClass(cls);
    setShowConfirmModal(true);
  };

  // 确认删除班级
  const confirmDeleteClass = () => {
    if (selectedClass) {
      deleteClass(selectedClass.id);
      // 添加审计日志
      addAuditLog({
        action: 'DELETE_CLASS',
        entity: 'class',
        entityId: selectedClass.id,
        details: `删除班级: ${selectedClass.name}`
      });
      setShowConfirmModal(false);
      setSelectedClass(null);
    }
  };

  // 保存班级信息（添加或编辑）
  const handleSaveClass = (classData: Omit<Class, 'id'>) => {
    if (isEditing && selectedClass) {
      // 编辑现有班级
      updateClass(selectedClass.id, classData);
      // 添加审计日志
      addAuditLog({
        action: 'UPDATE_CLASS',
        entity: 'class',
        entityId: selectedClass.id,
        details: `更新班级: ${selectedClass.name} -> ${classData.name}`
      });
    } else {
      // 添加新班级
      const newClassId = addClass(classData);
      // 添加审计日志
      addAuditLog({
        action: 'ADD_CLASS',
        entity: 'class',
        entityId: newClassId,
        details: `添加班级: ${classData.name}`
      });
    }
    setShowAddEditModal(false);
    setSelectedClass(null);
  };

  // 生成页码数组
  const generatePageNumbers = () => {
    const pages = [];
    const maxVisiblePages = 5;
    let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

    if (endPage - startPage + 1 < maxVisiblePages) {
      startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }

    for (let i = startPage; i <= endPage; i++) {
      pages.push(i);
    }
    return pages;
  };

  return (
    <div className="class-management-container">
      <div className="page-header">
        <h1>班级管理</h1>
        <div className="header-actions">
          <button className="add-class-btn" onClick={handleAddClass}>
            添加班级
          </button>
        </div>
      </div>

      <div className="filter-section">
        <div className="search-box">
          <input
            type="text"
            placeholder="搜索班级名称、编号、导员或讲师..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="search-input"
          />
        </div>
        <div className="filter-controls">
          <select
            value={selectedStage}
            onChange={(e) => setSelectedStage(e.target.value)}
            className="stage-select"
          >
            <option value="">所有阶段</option>
            <option value="专业阶段">专业阶段</option>
            <option value="专高阶段">专高阶段</option>
            <option value="实训阶段">实训阶段</option>
          </select>
          <select
            value={selectedAcademy}
            onChange={(e) => setSelectedAcademy(e.target.value)}
            className="academy-select"
          >
            <option value="">所有学院</option>
            <option value="人工智能">人工智能</option>
            <option value="数智传媒">数智传媒</option>
            <option value="鸿蒙生态开发">鸿蒙生态开发</option>
            <option value="云计算">云计算</option>
            <option value="元宇宙">元宇宙</option>
            <option value="市场部">市场部</option>
          </select>
          <select
            value={selectedStatus}
            onChange={(e) => setSelectedStatus(e.target.value)}
            className="status-select"
          >
            <option value="">所有状态</option>
            <option value="active">在读</option>
            <option value="graduated">毕业</option>
            <option value="disbanded">已解散</option>
            <option value="preparing">筹备中</option>
          </select>
        </div>
      </div>

      <div className="class-table-container">
        <ClassTable
          classes={currentClasses}
          onViewDetail={handleViewDetail}
          onEdit={handleEditClass}
          onDelete={handleDeleteClass}
        />
      </div>

      <div className="pagination-section">
        <div className="pagination-info">
          显示第 {indexOfFirstItem + 1} 到 {Math.min(indexOfLastItem, filteredClasses.length)} 条，共 {filteredClasses.length} 条记录
        </div>
        <div className="pagination-controls">
          <select
            value={itemsPerPage}
            onChange={handleItemsPerPageChange}
            className="items-per-page-select"
          >
            {itemsPerPageOptions.map(option => (
              <option key={option} value={option}>
                每页 {option} 条
              </option>
            ))}
          </select>
          <div className="page-buttons">
            <button
              onClick={goToFirstPage}
              disabled={currentPage === 1}
              className="page-btn"
            >
              首页
            </button>
            <button
              onClick={() => handlePageJump(currentPage - 1)}
              disabled={currentPage === 1}
              className="page-btn"
            >
              上一页
            </button>
            {generatePageNumbers().map(page => (
              <button
                key={page}
                onClick={() => handlePageJump(page)}
                className={`page-btn ${currentPage === page ? 'active' : ''}`}
              >
                {page}
              </button>
            ))}
            <button
              onClick={() => handlePageJump(currentPage + 1)}
              disabled={currentPage === totalPages}
              className="page-btn"
            >
              下一页
            </button>
            <button
              onClick={goToLastPage}
              disabled={currentPage === totalPages}
              className="page-btn"
            >
              末页
            </button>
          </div>
        </div>
      </div>

      {/* 添加/编辑班级模态框 */}
      <AddEditClassModal
        isOpen={showAddEditModal}
        onClose={() => setShowAddEditModal(false)}
        onSave={handleSaveClass}
        initialData={selectedClass}
        isEditing={isEditing}
      />

      {/* 确认删除模态框 */}
      <ConfirmModal
        isOpen={showConfirmModal}
        onClose={() => setShowConfirmModal(false)}
        onConfirm={confirmDeleteClass}
        title="确认删除"
        message={`确定要删除班级「${selectedClass?.name}」吗？此操作不可撤销。`}
      />

      {/* 班级详情模态框 */}
      <ClassDetailModal
        isOpen={showDetailModal}
        onClose={() => setShowDetailModal(false)}
        classData={selectedClass}
      />
    </div>
  );
};

export default ClassPage;